package com.woniuxy.threeproject.end_water_project_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.threeproject.end_water_project_user.commons.LateFeeCal;
import com.woniuxy.threeproject.end_water_project_user.commons.Result;
import com.woniuxy.threeproject.end_water_project_user.dao.MeterreadingMapper;
import com.woniuxy.threeproject.end_water_project_user.dao.PaymentDetailMapper;
import com.woniuxy.threeproject.end_water_project_user.dao.PaymentFormMapper;
import com.woniuxy.threeproject.end_water_project_user.domain.Meterreading;
import com.woniuxy.threeproject.end_water_project_user.domain.PaymentDetail;
import com.woniuxy.threeproject.end_water_project_user.domain.PaymentForm;
import com.woniuxy.threeproject.end_water_project_user.domain.User;
import com.woniuxy.threeproject.end_water_project_user.dao.UserMapper;
import com.woniuxy.threeproject.end_water_project_user.domain.form.UserQuerResult;
import com.woniuxy.threeproject.end_water_project_user.exception.EndWaterRuntimeException;
import com.woniuxy.threeproject.end_water_project_user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2021-08-25
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    public UserMapper userMapper;
    @Resource
    private MeterreadingMapper meterreadingMapper;
    @Resource
    private PaymentFormMapper paymentFormMapper;
    @Resource
    private PaymentDetailMapper paymentDetailMapper;
    @Override
    public User getUser(String card) {

        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.eq("card",card);
        User user = userMapper.selectOne(qw);
        return user;
    }

    //用户水费查询，账号验证
    @Override
    public Result findQueryUser(String card, String idCard) {
        log.info("水费查询，开始执行用户账号验证 ｛} {}",card,idCard);
        User user = getUser(card);
        if (null == user) {
            log.warn("查询失败：没有该用户");
            throw new EndWaterRuntimeException("查询失败：没有该用户");
        }
        String idc = user.getIdCard();
        if (!idc.substring(idc.length()-6,idc.length()).equals(idCard)){
            log.warn(""+idc.substring(idc.length()-6,idc.length()));
            log.warn("查询失败：验证码不正确");
            throw new EndWaterRuntimeException("查询失败：验证码不正确");
        }
        log.info("验证成功，开始执行查询业务");
        QueryWrapper<Meterreading> qw = new QueryWrapper<>();
        qw.eq("water_meter_id",user.getWaterMeterId());
        qw.eq("state",0);
        List<Meterreading> meterreadings = meterreadingMapper.selectList(qw);
        if(meterreadings.size() == 0){
            throw new EndWaterRuntimeException("用户么有需要缴纳的账单");
        }
        Double price = meterreadings.get(0).getPrice();//单价
        Double waterNum = LateFeeCal.waterNumtotal(meterreadings);//总水量
        Double latefee = LateFeeCal.lateFee(meterreadings);//滞纳金


        UserQuerResult userQuerResult = new UserQuerResult();
        userQuerResult.setCard(user.getCard());
        userQuerResult.setUserName(user.getUserName());
        userQuerResult.setPhone(user.getPhone());
        userQuerResult.setWaterMeterId(user.getWaterMeterId());
        userQuerResult.setWaterNum(waterNum);
        userQuerResult.setPrice(price);
        userQuerResult.setLateFee(latefee);
        userQuerResult.setPayMonth(meterreadings.size());
        userQuerResult.setOwe(waterNum*price+latefee);
        return Result.success(userQuerResult);
    }

    //用户缴费历史查询，账号验证
    @Override
    public Result findPaymentForm(String card, String idCard) {
        User user = userCheck(card, idCard);
        QueryWrapper<PaymentForm> qw = new QueryWrapper<>();
        qw.eq("user_id",user.getUserId());
        List<PaymentForm> paymentForms = paymentFormMapper.selectList(qw);
        if(paymentForms.size() == 0){
            throw new EndWaterRuntimeException("用户没有账单");
        }
        ArrayList<UserQuerResult> userQuerResults = new ArrayList<>();
        int length = paymentForms.size();
        for (int i = 0; i < length ; i ++){
            PaymentForm paymentForm = paymentForms.get(i);
            QueryWrapper<PaymentDetail> qwpd = new QueryWrapper<>();
            List<PaymentDetail> paymentDetails = paymentDetailMapper.selectList(qwpd);
            Double waterNum = LateFeeCal.waterNumtotalP(paymentDetails);//总水量
            Double price = paymentDetails.get(0).getPrice();//单价

            UserQuerResult userQuerResult = new UserQuerResult();
            userQuerResult.setCard(user.getCard());
            userQuerResult.setUserName(user.getUserName());
            userQuerResult.setPhone(user.getPhone());
            userQuerResult.setWaterMeterId(user.getWaterMeterId());
            userQuerResult.setWaterNum(waterNum);
            userQuerResult.setPrice(price);
            userQuerResult.setPayMonth(paymentForm.getPayMonth());
            userQuerResult.setHistoryMoney(paymentForm.getBillMoney());
            userQuerResult.setPayWay(paymentForm.getPayWay());
            userQuerResult.setState(paymentForm.getState());
            userQuerResults.add(userQuerResult);
        }

        return Result.success("2002","查询成功",userQuerResults);
    }
    private User userCheck(String card, String idCard){
        log.info("水费查询，开始执行用户账号验证 ｛} {}",card,idCard);
        User user = getUser(card);
        if (null == user) {
            log.warn("查询失败：没有该用户");
            throw new EndWaterRuntimeException("查询失败：没有该用户");
        }
        String idc = user.getIdCard();
        if (!idc.substring(idc.length()-6,idc.length()).equals(idCard)){
            log.warn(""+idc.substring(idc.length()-6,idc.length()));
            log.warn("查询失败：验证码不正确");
            throw new EndWaterRuntimeException("查询失败：验证码不正确");
        }
        log.info("验证成功，开始执行查询业务");
        return  user;
    }

    @Override
    public User addUser(User u) {
        log.info("service  开始新增用户表");
        log.info("{}",u);
        int i = userMapper.insert(u);
        if(i>0){
            return u;
    }else{
        throw  new EndWaterRuntimeException("service用户表添加时报错！");
    }

    }
}
